import asyncio
import re
import time
from itertools import zip_longest

from pyppeteer import launch

async def main():
    # 启动浏览器
    browser = await launch(executablePath='C:\Program Files\Google\Chrome\Application\chrome.exe')
    # 新建一个页面
    page = await browser.newPage()
    # 访问指定网址
    await page.goto('http://meps-k.com/',timeout=600000000000)
    # 获取页面数据
    content = await page.content()
    # print(content)
    #re获取商品名称
    pattern_name = r'h-\[34px\]">(.*?)</div'
    goods_name_list=re.findall(pattern_name,content,flags=re.S)
    # 接受循环后的商品名称
    goods_name=[]
    get_goods_name=[s.replace('\n','').strip() for  s in goods_name_list]
    for i in get_goods_name:
        goods_name_temp=i.find('>')
        if goods_name_temp !=1:
            goods_name_temp1=i[goods_name_temp +1 :]
            goods_name.append(goods_name_temp1)
    print(goods_name)

    # 获取商品销售价
    pattern_sell_price=r'class="text-\[#3C3C3C\] font-bold text-\[14px\]">(.*?)</span>'
    goods_price_list=re.findall(pattern_sell_price,content,flags=re.S)
    # print(goods_price_list)
    sell_of_goods=[s.replace('\n','') for s in goods_price_list]
    sell_of_goods=[s.replace(' ','') for s in sell_of_goods]
    # print(sell_of_goods)
    # 获取商品原价
    pattern_cost_price=r'class="text-\[#85878C\] ml-10px text-\[12px\]">(.*?)</del>'
    goods_price_list = re.findall(pattern_cost_price, content, flags=re.S)
    # print(goods_price_list)
    cost_of_goods = [s.replace('\n', '') for s in goods_price_list]
    cost_of_goods = [s.replace(' ', '') for s in cost_of_goods]
    # print(cost_of_goods)
    # cost_of_goods=[s for s in cost_of_goods if s]  #当有些商品销售价等于原价时，原价为'',去除''。
    # 关闭浏览器
    await browser.close()
    return [goods_name,sell_of_goods,cost_of_goods]
# 运行异步函数
resp=asyncio.get_event_loop().run_until_complete(main())
# 获取爬取后的商品信息
# print(resp)
for goods_name , sell_of_goods,cost_of_goods  in zip_longest (resp[0],resp[1],resp[2]):
    if not cost_of_goods:
        cost_of_goods=sell_of_goods
    print('商品名称：{}，商品销售价：{}，商品成本价：{}'.format(goods_name,sell_of_goods,cost_of_goods))